#!/bin/bash

SWNAME=dbeaver
# SWVER=18.2.3

# 注意安装顺序，后装者依赖前装者
DEB_PATH1=./downloads/${SWNAME}.tar.gz

DIR_DESKTOP_FILES=/usr/share/applications
DSK_FILE=${SWNAME}.desktop
DSK_PATH=${DIR_DESKTOP_FILES}/${DSK_FILE}
app_dir=/opt/apps/${SWNAME}

action=$1
if [ "$action" == "" ]; then action=安装; fi

. ./scripts/common.sh

function sw_download() {
	tmpdns=`cd /exbin && droidexec ./vm_getHostByName.sh ${GITHUB_PROXY_HOST}`
	exit_if_fail $? "DNS解析失败"
	echo "$tmpdns" >> /etc/hosts

	case "${CURRENT_VM_ARCH}" in
		"arm64")
			# https://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/pool/universe/k/kdenlive/
			swUrl="${GITHUB_PROXY_HTTP}https://github.com/dbeaver/dbeaver/releases/download/24.1.0/dbeaver-ce-24.1.0-linux.gtk.aarch64-nojdk.tar.gz"
			download_file2 "${DEB_PATH1}" "${swUrl}"
			exit_if_fail $? "下载失败，网址：${swUrl}"
		;;
		"amd64")
			swUrl="${GITHUB_PROXY_HTTP}https://github.com/dbeaver/dbeaver/releases/download/24.1.0/dbeaver-ce-24.1.0-linux.gtk.x86_64-nojdk.tar.gz"
			download_file2 "${DEB_PATH1}" "${swUrl}"
			exit_if_fail $? "下载失败，网址：${swUrl}"
		;;
		*) exit_unsupport ;;
	esac
}

function sw_install() {

	mkdir -p ${app_dir}

	echo "正在解压. . ."
	tar -xzf ${DEB_PATH1} --overwrite -C /opt/apps/
	exit_if_fail $? "安装失败，软件包：${DEB_PATH1}"

}

function sw_create_desktop_file() {
	echo "正在生成桌面文件"

	tmpfile=${DIR_DESKTOP_FILES}/${SWNAME}.desktop
	cat <<- EOF > ${tmpfile}
		[Desktop Entry]
		Name=${SWNAME}
		GenericName=${SWNAME}
		Exec=${app_dir}/${SWNAME}
		Icon=${app_dir}/icon.xpm
		Terminal=false;
		Type=Application
	EOF
	cp2desktop ${tmpfile}

	gxmessage -title "提示"     $'\n安装完成\n\n'  -center
}

if [ "${action}" == "卸载" ]; then
	# echo "暂不支持卸载"
	# exit 1
	rm -rf ${DEB_PATH1}

	rm -rf /usr/bin/${SWNAME}

	rm -rf /opt/apps/${SWNAME}

	rm2desktop ${SWNAME}.desktop

	apt-get clean
else

	which java >/dev/null 2>&1
	if [ $? -ne 0 ]; then
		echo ""				> /tmp/msg.txt
		echo "请先安装jdk21">>/tmp/msg.txt
		echo ""				>>/tmp/msg.txt
		gxmessage -title "提示" -file /tmp/msg.txt -center
		exit 1
	fi

	sw_download
	sw_install
	sw_create_desktop_file
fi

